package com.example.demo.util;


import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author wunan
 */
public class AesUtil2 {

    /**
     * 密钥 (需要前端和后端保持一致)32位作为密钥
     */
    private static final String PASWORD = "4da57244202e4968bca701f49e8acc1a";

    /**
     * 算法
     */
    private static final String ALGORITHMS = "AES/GCM/PKCS5Padding";


    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return new byte[0];
        }

        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /***
     * aes-128-gcm 加密
     * @param msg 为加密信息
     * @return 返回base64编码，也可以返回16进制编码
     **/
    public static String aesEncrypt(String msg) {

        try {
            byte[] sSrc = msg.getBytes(StandardCharsets.UTF_8); //修改添加字符集
            byte[] sKey = parseHexStr2Byte(PASWORD);
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance(ALGORITHMS);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            //这边是获取一个随机的iv 默认为12位的
            byte[] iv = cipher.getIV();
            //执行加密
            byte[] encryptData = cipher.doFinal(sSrc);
            //这边进行拼凑 为 iv + 加密后的内容
            byte[] message = new byte[12 + sSrc.length + 16];
            System.arraycopy(iv, 0, message, 0, 12);
            System.arraycopy(encryptData, 0, message, 12, encryptData.length);

            return Base64.getEncoder().encodeToString(message);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |
                BadPaddingException e) {
            return null;
        }

    }

    /***
     * aes-128-gcm 解密
     * @return msg 返回字符串
     */
    public static String aesDecrypt(String encryptStr) {

        try {
            byte[] sSrc = Base64.getDecoder().decode(encryptStr);
            byte[] sKey = parseHexStr2Byte(PASWORD);

            GCMParameterSpec iv = new GCMParameterSpec(128, sSrc, 0, 12);
            Cipher cipher = Cipher.getInstance(ALGORITHMS);
            SecretKey key2 = new SecretKeySpec(sKey, "AES");

            cipher.init(Cipher.DECRYPT_MODE, key2, iv);

            //这边和nodejs不同的一点是 不需要移除后面的16位
            byte[] decryptData = cipher.doFinal(sSrc, 12, sSrc.length - 12);

            return new String(decryptData, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException |
                InvalidAlgorithmParameterException | InvalidKeyException e) {
            return null;
        }

    }


    public static void main(String[] args) {

        String encryptData = "abIy1mROFmXriyH4rLq461CUUIqtQIeadEPsKs2lSqjG+dGBbhCQJJvCcMaXo2lVOnhkftMhArzZUFJj6y+RnPAZaK5IskfD2Jcnv4VsoOY31njT+0lYA11UvV/xWX81qnteTA/etiD27okwXqHLNse0L4MoBMCKe68W+77BjjNO/TfNNfxDNjdRHpJAolsASF7OB3l1u7BFNAgNV9OjtXjkHbkdjI0MRd4ittRIeQ4xWsy9eJQhLk1maApcg8Q3";

        System.out.println(aesDecrypt(encryptData));
    }
}